<template>
  <div>
    <div class="top">
      <el-input class="rolename" v-model="role.param.rolename" placeholder="请输入角色名称"></el-input>
        <el-button type="primary" @click="initData" icon="el-icon-search" v-show="this.hasPermission('role:query')">查询</el-button>
        <el-button type="primary" @click="show('新增角色信息',null,false)" icon="el-icon-plus" v-show="this.hasPermission('role:add')">新增</el-button>
        <el-button type="danger" @click="deletes" icon="el-icon-delete" :disabled="this.multipleSelection.length==0" v-show="this.hasPermission('role:delete')">批量删除</el-button>
    </div>
    <div style="margin-top: 10px;">
      <template>
        <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
            :data="tableData"
            style="width: 100%"
            border
            @selection-change="handleSelectionChange"
            max-height="450">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="rolename"
              label="角色名称"
              >
          </el-table-column>
          <el-table-column
              prop="status"
              label="状态"
              width="120">
            <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#02538C"
                  inactive-color="#B9B9B9"
                  @change="changeSwitch(scope.row)"/>
            </template>

          </el-table-column>

          <el-table-column
              fixed="right"
              label="操作"
              width="350">
            <template slot-scope="scope">
              <el-button class="el-icon-search" @click="show('查看角色信息',scope.row,true)" type="primary" size="small">查看</el-button>
              <el-button class="el-icon-edit" @click="show('编辑角色信息',scope.row,false)" type="primary"  size="small">编辑</el-button>
              <el-button class="el-icon-edit" @click="showPermssion(scope.row)" type="primary"  size="small">权限</el-button>

              <el-button class="el-icon-delete" @click="deleteById(row)"  type="warning" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
     <div style="text-align: right">
       <el-pagination
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           :current-page="role.pageNumber"
           :page-sizes="[20,100,200,300]"
           :page-size="role.pageSize"
           layout="total, sizes, prev, pager, next, jumper"
           :total="400">
       </el-pagination>
     </div>
    </div>
    <div id="roleInfo">
      <el-dialog :title="title" :visible.sync="dialogFormVisible">

        <el-form :model="form" v-loading="loading" :readOnly="readOnly">
          <el-form-item label="角色名称" label-width="120px">
            <el-input v-model="form.rolename" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="" label-width="120px">
            <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="1"
                active-text="启用"
                inactive-value="0"
                inactive-text="停用">

            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </el-dialog>
    </div>
    <div id="permission">
      <el-dialog title="角色权限" :visible.sync="dialogTableVisible">
        <el-tree
            :data="tdata"
            show-checkbox
            node-key="id"
            ref="tree"
            @check="this.getCheckedNodes"
            :default-expanded-keys="[2, 3]"
            :default-checked-keys="defaultCheckedKeys"
            :props="defaultProps">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="savePermission">保 存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
name: "Role",
  data(){
    return {
      role:{
        param:{
          rolename:''
        },
        pageNumber:1,
        pageSize:20,
        total:0
      },
      curRoleId:0,
      form:{
        rolename:'',
        id:0,
        status:'1'
      },
      tableData:[],
      fmData:[],
      dialogFormVisible:false,
      dialogTableVisible:false,
      loading:true,
      title:'',
      readOnly:false,
      multipleSelection: [],
      defaultCheckedKeys:[],
      tdata: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.role.pageSize=parseInt(val);
      this.initData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.role.pageNumber = parseInt(val);
      this.initData();
    },
    initData(){

      this.postRequest('/sys/role/query',this.role).then(resp=>{
        if(resp.success){
            this.tableData = resp.result.list;
            this.role.total=resp.result.total;

        }
        this.loading = false

      })
    },
    show(title,row,readOnly){
      this.title = title
      this.readOnly = readOnly
      this.dialogFormVisible=true
      if(row!=null){
        this.getRequest('/sys/role/info/'+row.id).then(resp=>{
          this.form = resp.result;
          this.form.status = resp.result.status+''
          this.loading = false;
        })
      }

    },
    handleSelectionChange(val){

      this.multipleSelection = val

    },
    deleteById(row){
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest('/sys/role/deletes?ids='+row.id).then(resp=>{
          if(resp.success){
            this.initData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deletes(){
      this.$confirm('此操作将永久删除'+this.multipleSelection.length+'个角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids='?';
        this.multipleSelection.forEach(item=>{
          ids+='ids='+item.id+'&';
        });
        this.deleteRequest('/sys/role/deletes'+ids).then(resp=>{
          if(resp.success){
            this.initData()
          }
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    close(){
      this.dialogFormVisible = false;
      this.$refs.form1.resetFields()
    },
    changeSwitch(row){
      let role={id:row.id,status:row.status}
      this.postRequest('/sys/role/save',role).then(resp=>{
        if(resp.success){
          this.initData();


        }
      })
    },
    save(){
      this.postRequest('/sys/role/save',this.form).then(resp=>{
         if(resp.success){
           this.initData();
           this.close();

         }
      })
    },
    showPermssion(row){
      this.dialogTableVisible = true;
      // 树加载
      this.getRequest('/sys/role/role/resourceJsonData?roleId='+row.id).then(resp=>{
        this.tdata = resp.result;
        this.fmtCheckKey(this.tdata);
        this.defaultCheckedKeys = this.fmData
        this.curRoleId = row.id
      })
    },
    getCheckedNodes(p1,p2) {

      let zi = this.$refs.tree.getCheckedKeys()//返回选中子节点的key
      let fu =this.$refs.tree.getHalfCheckedKeys()
      console.log(this.$refs.tree.getCheckedNodes().length);
    },
    fmtCheckKey(data){

      data.forEach(item=>{
        if(item.checked){

          if(item.parent){
            // 如果父选中，判断所有子选中了吗？
            this.checkParentChecked(item)
          }

        }
      })

    },
    checkParentChecked(data){
      let temp=0;
      let child = data.children;
      let child_temp=0;
      for(let i=0;i<child.length;i++){
        // 获取所有子
        // 看子有孙吗？
        let child_=child[i];

        if(child_.parent){
          let child2 = child_.children;//孙
          let child2_temp=0
          if(child2!=null){

              for(let j=0;j<child2.length;j++){
                if(child2[j].checked){
                  this.fmData.push(child2[j].id)
                  child2_temp++
                }
              }


          if(child2_temp==child2.length){
            this.fmData.push(child2.id);
            child_temp++
          }
          }else{
            if(child_.checked){
              this.fmData.push(child_.id);
              child_temp++
            }
          }
        }

      }
      if(child_temp==child.length){
        this.fmData.push(child.id);
      }
    },
    savePermission(){
      let keys = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
     console.log(keys.length)
      let resourceId='?roleId='+this.curRoleId+'&'
      for(var i=0;i<keys.length;i++){
        resourceId+='resourceIds='+keys[i]+'&'
      }
      this.getRequest('/sys/role/savePermission'+resourceId).then(resp=>{
        if(resp.success){
          this.curRoleId=0
          this.dialogTableVisible = false
        }
      })
    }


  }
}
</script>

<style scoped>
.top{
  display: flex;
}
.rolename{
  width: 200px;
  margin-right: 10px;
}
</style>